from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import Mapped, mapped_column

app = Flask(__name__)

HOSTNAME = "127.0.0.1"
POST = 3306
USERNAME = "root"
PASSWORD = "Zhang630901"
DATABASE = "mysql"

app.config[
    'SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{POST}/{DATABASE}?charset=utf8mb4"

db = SQLAlchemy(app)


class PlayerInfo(db.Model):
    __tablename__ = "playerinfo"
    id: Mapped[int] = mapped_column(primary_key=True)
    username: Mapped[str] = mapped_column(db.String(100), nullable=False)
    password: Mapped[str] = mapped_column(db.String(100), nullable=False)


with app.app_context():
    db.create_all()


@app.route("/user/add")
def user_add():
    user = PlayerInfo(username="demo1", password="22")
    db.session.add(user)
    db.session.commit()
    return "添加成功"


@app.route("/user/get_all")
def user_get_all():
    all_users = db.session.query(PlayerInfo).all()
    info = ""
    for user in all_users:
        info = info + "userName:" + user.username + ";password:" + user.password + ";"
    return f"查询到的所有数据：{info}"


@app.route("/user/update_user")
def user_update():
    uid = request.args.get('uid')
    print(f"uid:{uid}")
    user = db.session.query(PlayerInfo).filter(PlayerInfo.username == uid).first()
    player = PlayerInfo.query.get(1)
    print(f"player:{player.id}")
    if user is not None:
        print("修改数据")
        user.verified = True
        user.password = "3333"
        db.session.commit()
        return f"操作成功:{uid}"
    return f"更新失败:{uid}"

@app.route("/user/demo/<uid>")
def user_demo(uid):
    return f"uid:{uid}"

# 测试是否连接成功
with app.app_context():
    with db.engine.connect() as conn:
        print("连接成功")
